<template>
  <div class="grade-view">
    <div class="header">
      <h2>我的成绩</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-row">
          <div class="form-group">
            <label>学年：</label>
            <el-select v-model="searchForm.academicYear" placeholder="请选择学年" clearable>
              <el-option label="2024-2025" value="2024-2025" />
              <el-option label="2023-2024" value="2023-2024" />
              <el-option label="2022-2023" value="2022-2023" />
            </el-select>
          </div>
          <div class="form-group">
            <label>学期：</label>
            <el-select v-model="searchForm.semester" placeholder="请选择学期" clearable>
              <el-option label="第一学期" value="第一学期" />
              <el-option label="第二学期" value="第二学期" />
            </el-select>
          </div>
          <div class="form-group">
            <label>课程名称：</label>
            <el-input v-model="searchForm.courseName" placeholder="请输入课程名称" clearable />
          </div>
        </div>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 成绩统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalCourses }}</div>
          <div class="stat-label">总课程数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon success">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ passedCourses }}</div>
          <div class="stat-label">已通过</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon warning">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ failedCourses }}</div>
          <div class="stat-label">未通过</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon primary">
          <el-icon><Star /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ averageScore }}</div>
          <div class="stat-label">平均分</div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        stripe 
        border
        v-loading="loading"
      >
        <el-table-column prop="courseName" label="课程名称" width="180" />
        <el-table-column prop="teacherName" label="任课教师" width="120" />
        <el-table-column prop="academicYear" label="学年" width="100" />
        <el-table-column prop="semester" label="学期" width="100" />
        <el-table-column prop="usualScore" label="平时成绩" width="100">
          <template #default="scope">
            <span class="score-text">{{ scope.row.usualScore || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="examScore" label="考试成绩" width="100">
          <template #default="scope">
            <span class="score-text">{{ scope.row.examScore || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalScore" label="总成绩" width="100">
          <template #default="scope">
            <span class="score-text total-score">{{ scope.row.totalScore || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="letterGrade" label="等级" width="80">
          <template #default="scope">
            <el-tag :type="getGradeTagType(scope.row.letterGrade)" size="large">
              {{ scope.row.letterGrade || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 成绩详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="成绩详情"
      width="500px"
    >
      <div class="grade-detail" v-if="selectedGrade">
        <div class="detail-section">
          <h4>课程信息</h4>
          <div class="detail-row">
            <span class="label">课程名称：</span>
            <span class="value">{{ selectedGrade.courseName }}</span>
          </div>
          <div class="detail-row">
            <span class="label">任课教师：</span>
            <span class="value">{{ selectedGrade.teacherName }}</span>
          </div>
          <div class="detail-row">
            <span class="label">学年学期：</span>
            <span class="value">{{ selectedGrade.academicYear }} {{ selectedGrade.semester }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>成绩信息</h4>
          <div class="score-grid">
            <div class="score-item">
              <div class="score-label">平时成绩</div>
              <div class="score-value">{{ selectedGrade.usualScore || '--' }}</div>
            </div>
            <div class="score-item">
              <div class="score-label">考试成绩</div>
              <div class="score-value">{{ selectedGrade.examScore || '--' }}</div>
            </div>
            <div class="score-item total">
              <div class="score-label">总成绩</div>
              <div class="score-value">{{ selectedGrade.totalScore || '--' }}</div>
            </div>
            <div class="score-item grade">
              <div class="score-label">等级</div>
              <div class="score-value">
                <el-tag :type="getGradeTagType(selectedGrade.letterGrade)" size="large">
                  {{ selectedGrade.letterGrade || '--' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-section" v-if="selectedGrade.reviewComment">
          <h4>审核意见</h4>
          <div class="review-comment">
            {{ selectedGrade.reviewComment }}
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Check, Warning, Star } from '@element-plus/icons-vue'
import { gradeStudentApi } from '@/api/grade'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const selectedGrade = ref(null)

// 搜索表单
const searchForm = reactive({
  academicYear: '',
  semester: '',
  courseName: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 统计数据
const totalCourses = computed(() => tableData.value.length)
const passedCourses = computed(() => tableData.value.filter(item => item.letterGrade && item.letterGrade !== 'F').length)
const failedCourses = computed(() => tableData.value.filter(item => item.letterGrade === 'F').length)
const averageScore = computed(() => {
  const validScores = tableData.value.filter(item => item.totalScore).map(item => parseFloat(item.totalScore))
  if (validScores.length === 0) return '--'
  const sum = validScores.reduce((acc, score) => acc + score, 0)
  return (sum / validScores.length).toFixed(1)
})

// 页面加载时获取数据
onMounted(() => {
  loadGrades()
})

// 加载成绩列表
const loadGrades = async () => {
  loading.value = true
  try {
    // 检查用户登录状态和角色
    if (!userStore.currentUser) {
      console.error('用户未登录')
      ElMessage.error('请先登录')
      return
    }
    
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    
    console.log('=== 学生成绩查询参数 ===')
    console.log('当前用户:', userStore.currentUser)
    console.log('用户ID:', userStore.currentUser?.id)
    console.log('用户角色:', userStore.currentUser?.roles)
    console.log('请求参数:', params)
    
    const response = await gradeStudentApi.getStudentGrades(params)
    
    console.log('=== API响应 ===')
    console.log('响应数据:', response)
    console.log('响应code:', response.code)
    console.log('响应data:', response.data)
    
    if (response.code === 200) {
      console.log('进入成功分支')
      console.log('records:', response.data.records)
      console.log('total:', response.data.total)
      
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
      
      console.log('设置后的tableData:', tableData.value)
      console.log('设置后的total:', pagination.total)
      
      if (tableData.value.length === 0) {
        console.log('没有找到成绩数据')
        ElMessage.info('暂无成绩数据')
      } else {
        console.log(`成功加载 ${tableData.value.length} 条成绩记录`)
      }
    } else {
      console.log('进入失败分支，code:', response.code, '消息:', response.message)
      ElMessage.error(response.message || '获取成绩列表失败')
    }
  } catch (error) {
    console.error('=== 请求错误 ===')
    console.error('错误详情:', error)
    console.error('错误响应:', error.response)
    
    let errorMessage = '获取成绩列表失败'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadGrades()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 查看详情
const handleDetail = (row) => {
  selectedGrade.value = row
  detailDialogVisible.value = true
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadGrades()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadGrades()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '--'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已保存',
    2: '已送审',
    3: '已确认',
    4: '已退回'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'success',
    4: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取成绩等级标签类型
const getGradeTagType = (grade) => {
  const typeMap = {
    'A': 'success',
    'B': 'primary',
    'C': 'warning',
    'D': 'info',
    'F': 'danger'
  }
  return typeMap[grade] || 'info'
}
</script>

<style scoped>
.grade-view {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form .form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-group label {
  white-space: nowrap;
  font-weight: 500;
}

.button-group {
  display: flex;
  gap: 10px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #409eff;
  color: white;
  font-size: 24px;
}

.stat-icon.success {
  background: #67c23a;
}

.stat-icon.warning {
  background: #e6a23c;
}

.stat-icon.primary {
  background: #409eff;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.score-text {
  font-weight: 500;
}

.total-score {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.grade-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.detail-row {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.detail-row .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.detail-row .value {
  color: #303133;
}

.score-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.score-item {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  text-align: center;
}

.score-item.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.score-item.grade {
  background: #f0f9ff;
}

.score-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.score-item.total .score-label {
  color: rgba(255, 255, 255, 0.8);
}

.score-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.score-item.total .score-value {
  color: white;
}

.review-comment {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  color: #606266;
  line-height: 1.6;
}
</style> 